import React from 'react';
import {
  AppRegistry,
  Environment,
  StyleSheet,
  Image,
  Text,
  View,
  VrButton,
  NativeModules
} from 'react-360'
import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter';

function loadImage (src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
      resolve(img);
    };
    img.onerror = function (err) {
      reject(err);
    };

    img.src = src;
  });
}

class Background extends React.Component {
  constructor(props) {
    super();
    // console.log(React360)
    // loadImage(props.uri).then(img => console.log('loaded', img))
    // Environment.setBackgroundImage(props.uri, {format: props.format});
    this.state = {
      uri: props.uri
    }
  }

  componentWillReceiveProps(nextProps) {
    if (
      nextProps.uri !== this.props.uri ||
      nextProps.format !== this.props.format
    ) {
      this.setState({
        // load: true,
        uri: nextProps.uri
      });
    }
  }

  onLoad = (evt) => {
    Environment.setBackgroundImage(this.state.uri, { format: this.props.format });
    // hide loading
    NativeModules.LoaderModule.hide()
  }

  onLoadStart = (evt) => {
    // show loading
    NativeModules.LoaderModule.show()
  }

  render() {
    console.log('render bg', this.state.uri)
    return <Image
      style={{display: 'none'}}
      source={{uri: this.state.uri}}
      onLoad={this.onLoad}
      onLoadStart={this.onLoadStart}
    />
  }
}

class Slideshow extends React.Component {
  state = {
    index: 0,
  };

  constructor(props) {
    super()
    props.thumbnails && NativeModules.ThumbnailsModule.init(props)
    props.navigation && NativeModules.NavigationModule.init(props)

    RCTDeviceEventEmitter.addListener('setBackground', this.showPhoto)

    // NativeModules.LoaderModule.show()

  }

  showPhoto = (index, photo) => {
    this.setState({ index });
    // Environment.setBackgroundImage(photo.uri, { format: photo.format });
  }

  _prevPhoto = () => {
    let next = this.state.index - 1;
    if (next < 0) {
      next += this.props.photos.length;
    }
    this.setState({
      index: next,
    });
  };

  _nextPhoto = () => {
    this.setState({
      index: this.state.index + 1,
    });
  };

  render() {
    console.log('rerender')
    const current = this.props.photos[this.state.index];
    return (
      <View style={styles.wrapper}>
        <Background uri={current.uri} format={current.format} />
      </View>
    );
  }
}
/*
<View style={styles.controls}>
          <VrButton onClick={this._prevPhoto} style={styles.button}>
            <Text style={styles.buttonText}>{'<'}</Text>
          </VrButton>
          <View>
            <Text style={styles.title}>{current.title}</Text>
          </View>
          <VrButton onClick={this._nextPhoto} style={styles.button}>
            <Text style={styles.buttonText}>{'>'}</Text>
          </VrButton>
        </View>
*/

/*
class App extends React.Component {

  constructor (props) {
    const photos = props.photos || []

    state = {
      ready: false,
      photos
    }
  }

  componentWillMount() {
    Linking.getInitialURL().then((url) => {

      const queries = qs.parse(url.split('?')[1])

      // let autoPlay = qs.parse(url.split('?')[1]).autoplay
      // encode的编码
      // this._source = decodeURIComponent(queries.source)
      // this.fetchData(this._source)
    })
  }

  fetchData (uri) {
    fetch(uri)
      .then(response => response.json())
      .then(data => {
        console.log(data)
        const photos = data.scenes.map(scene => {
          return {
            // uri: this.asset(scene.photopanos[0].src)
            uri: scene.photopanos[0].src,
            format: '2D'
          }
        })

        this.setState({
          ready: true,
          photos
        })
      })
  }

  asset (uri) {
    return uri.substr(0, 4) === 'http' ? { uri } : asset(uri)
  }

  render () {
    if (!this.state.ready) {
      return <View />
    }

    return <Slideshow photos={this.state.photos} />
  }
}

*/

const styles = StyleSheet.create({
  wrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 600,
    width: 1000,
  },
  controls: {
    // backgroundColor: 'rgba(0, 0, 0, 0.7)',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: 800,
    padding: 10,
  },
  title: {
    color: '#ffffff',
    textAlign: 'left',
    fontSize: 36,
    fontWeight: 'bold',
  },
  button: {
    backgroundColor: '#c0c0d0',
    borderRadius: 5,
    width: 40,
    height: 44,
  },
  buttonText: {
    textAlign: 'center',
    color: '#000000',
    fontSize: 30,
    fontWeight: 'bold',
  },
});

AppRegistry.registerComponent('Slideshow', () => Slideshow);
